package day240602;

import java.util.*;

@SuppressWarnings({"all"})
public class SetDemo2 {
    public static void main(String[] args) {
        // 问题：Set 是如何判断即将加入的元素跟之前的重复了？
        Set<CustomObj> customObjs = new HashSet<>();

        customObjs.add(new CustomObj("X", 1));
        customObjs.add(new CustomObj("Y", 2));
        customObjs.add(new CustomObj("Z", 3));

        customObjs.add(new CustomObj("Y", 2));

        System.out.println(customObjs.size());
        System.out.println(customObjs);

        // 如何让 customObjs.size() = 3
        // 思考：重写 CustomObj equals 方法
        /*System.out.println("=== === ===");
        // 上一个问题的简化（子问题。上节课没听的同学，先做这个子问题）

        HashSet<CustomObj> customObjs2 = new HashSet<>();
        customObjs2.add(new CustomObj("X", 1));
        customObjs2.add(new CustomObj("Y", 2));
        customObjs2.add(new CustomObj("Z", 3));

        // 如何让下面代码的运行结果返回 true
        System.out.println(customObjs2.contains(new CustomObj("Y", 2)));
        System.out.println("=== === ===");

        // 主动调用刚重写的 equals 方法
        CustomObj y1 = new CustomObj("Y", 3);
        CustomObj y2 = new CustomObj("Y", 3);
        System.out.println(y1.equals(y2));*/
    }
}

class CustomObj {
    String name;
    int value;

    public CustomObj(String name, int value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public String toString() {
        return "CustomObj{" +
                "name='" + name + '\'' +
                ", value=" + value +
                '}';
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CustomObj customObj = (CustomObj) o;
        return value == customObj.value && Objects.equals(name, customObj.name);
    }
    @Override
    public int hashCode() {
        //与Objects一样是工具类
        // Array => Arrays
        // Collection => Collections
        return Objects.hash(name, value);
    }
}